package com.gxa.controller.user;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.gxa.auth.OAuth2Token;
import com.gxa.common.constant.ScommunityConstant;
import com.gxa.common.utils.*;
import com.gxa.entity.user.SysUser;
import com.gxa.entity.user.User;
import com.gxa.entity.request.UserLoginRequest;

import com.gxa.service.user.SysUserService;
import com.gxa.service.user.UserService;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Map;

@Api(tags = "用户接口")
@RestController
public class UserController {

    @Autowired
    private SysUserService userService;

    @Autowired
    private RedisUtil redisUtil;

    @CrossOrigin(origins = "*", maxAge = 3600)//跨越请求配置
    @ApiOperation("登录接口")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "登录成功"),
            @ApiResponse(code = 306, message = "登录已超时，请重新登录"),
            @ApiResponse(code = 307, message = "令牌格式不正确"),
            @ApiResponse(code = 401, message = "没有权限"),
            @ApiResponse(code = 403, message = "无效请求，本系统只支持AJAX请求"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    @PostMapping("/user/login")
    public R login(@RequestBody UserLoginRequest user, HttpServletRequest request) {
        if (StringUtils.isBlank(user.getUserName()) || StringUtils.isBlank(user.getPwd())) {
            return R.error("用户名和密码不能为空!");
        }
        // 得到加密后的密码
        String passwordEncrypt = MD5Util.encrypt(user.getUserName(), user.getPwd());

        SysUser currentUser = userService.queryByUserName(user.getUserName());
        if (currentUser == null) {
            return R.error("用户名或者密码不正确！");
        }
        if (!passwordEncrypt.equals(currentUser.getPassword())) {
            return R.error("用户名或者密码不正确!");
        }
        if (ScommunityConstant.ACCOUNT_LOCK.equals(currentUser.getStatus())) {
            return R.error("账号已被锁定,请联系管理员！");
        }

        //登录成功 生成token
        // 加密签名
        String token = JWTUtils.sign(currentUser.getUsername(), passwordEncrypt);
        // 过期时间
        LocalDateTime expireTime = LocalDateTime.now().plusSeconds(86400L);
        String expireTimeStr = DateUtil.formatFullTime(expireTime);
        OAuth2Token oAuth2Token = new OAuth2Token(token,expireTimeStr);
        //获取ip
        String ip = IPUtil.getIpAddr(request);
        redisUtil.set(ScommunityConstant.ZHUIYI_TOKEN + token,token,86400L*1000);
        Map<String, Object> userInfo = this.userService.getUserWithToken(oAuth2Token, currentUser);
        System.out.println("userInfo:用户信息-----"+userInfo);
        return R.ok("登录成功!").put("user",userInfo);
    }

    @CrossOrigin(origins = "*", maxAge = 3600)//跨越请求配置
    @ApiOperation("测试用登录接口")
    @GetMapping("/user/testlogin")
    public R testlogin(@RequestParam String userName, @RequestParam String pwd) {
        System.out.println(userName);
        System.out.println("-------");
        System.out.println(pwd);
        if ("admin".equals(userName) && "admin".equals(pwd)) {
            User user = new User();
            user.setUserName("admin");
            return R.ok("登录成功").put("user",user);
        }else {
            return R.error(500,"用户名或密码错误");
        }

    }


//    @ApiOperation("注销接口")
//    @ApiResponses(value = {
//            @ApiResponse(code = 200, message = "注销成功"),
//            @ApiResponse(code = 306, message = "登录已超时，请重新登录"),
//            @ApiResponse(code = 307, message = "令牌格式不正确"),
//            @ApiResponse(code = 401, message = "没有权限"),
//            @ApiResponse(code = 403, message = "无效请求，本系统只支持AJAX请求"),
//            @ApiResponse(code = 500, message = "服务器内部错误")
//    })
//    @GetMapping("/user/logout")
//    public R logout() {
//        Subject subject = SecurityUtils.getSubject();
//        try {
//            subject.logout();
//            return R.ok("注销成功");
//        }catch (Exception e) {
//            e.printStackTrace();
//            throw new RRException("注销失败");
//        }
//    }
}
